<?php
	
	/**
	 *  PkDatabase class file.
	 * 
	 * @author Brian Bal <brian@youbeqb.com>
	 * @version 1.0
	 * @package pink-koala
	 */
	
	/**
	 * PkDatabase class
	 *
	 * @package pink-koala
	 * @author Brian Bal
	 **/
	
	class PkDatabase
	{
		static private $pk_database;
		static private $connection;
		static private $selected_db;
		static private $db_schema;
		
		// A private constructor; prevents direct creation of object
		private function __construct() 
		{
			self::$db_schema = array();
		}
		
		// generate the PkDatabase Instance
		static public function getPkDatabase()
		{
			if(! isset(self::$pk_database))
			{
				self::$pk_database = new PkDatabase();
			}
			
			return self::$pk_database;
		}
		
		// Prevent users to clone the instance
		public function __clone()
		{
			trigger_error('Cloning of PkDatabase is not allowed.', E_USER_ERROR);
		}
		
		public function connectToDatabase($db_host, $db_user, $db_password, $db_name)
		{
			self::$connection = mysql_connect($db_host, $db_user, $db_password);
			
			if (! self::$connection)
			{
				die('Could not connect: ' . mysql_error());
			}
			
			self::$selected_db = mysql_select_db($db_name, self::$connection);
		}
		
		public function closeDatabaseConnection()
		{
			mysql_close(self::$connection);
		}
		
		function useDatabase($db_name)
		{
			self::$selected_db = mysql_select_db($db_name);
		}
		
		public function loadSchema($table_name)
		{
			// build the query
			$sql = "DESCRIBE $table_name";
			
			//echo "<p>$sql</p>";
			
			$tmp = array();
			
			// run the query and get results
			$result = mysql_query($sql);
			if($result !== false)
			{
				while($row = mysql_fetch_assoc($result))
				{
					array_push($tmp, $row);
				}
			}
			
			self::$db_schema[$table_name] = $tmp;
			$tmp = null;
		}
		
		function tableSchema($table_name)
		{
			if(! isset(self::$db_schema[$table_name]) )
			{
				self::loadSchema($table_name);
			}
			
			/*
			echo "<pre>";
			print_r($db_schema[$table_name]);
			echo "</pre>";
			*/
			
			return self::$db_schema[$table_name];
		}
		
	}
	